package com.dk.controller;

import com.dk.service.SslPersonService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("loginController")
public class LoginController {

    @DubboReference
    private SslPersonService personService;


    @RequestMapping("login")
    @ResponseBody
    public Map login(HttpServletRequest request, String pname, String pwd, Model model) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "登陆成功");
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(pname, pwd);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            map.put("code", 1);
            map.put("msg", "未注册");
        } catch (IncorrectCredentialsException e) {
            map.put("code", 2);
            map.put("msg", "密码错误");
        }
        return map;

//        Map map = new HashMap();
//        TPerson person = personService.findPersonByName(pname);
//        if (person == null) {
//            map.put("code", 1);
//            map.put("msg", "账号不存在");
//            return map;
//        }
//        if (!pwd.equals(person.getPwd())) {
//            map.put("code", 2);
//            map.put("msg", "密码错误");
//            return map;
//        }
//        request.getSession().setAttribute("user", person);
//        map.put("code", 0);
//        map.put("msg", "登录成功");
//        return map;
    }
    @RequestMapping("toLogin")
    public String toLogin() {

        return "login";
    }

    @RequestMapping("show")
    public String show() {

        return "show";
    }

    @RequestMapping("zhuce")
    public String zhuce() {

        return "zhuce";
    }
    @RequestMapping("unauthorizedUrl")
    @ResponseBody
    public String unauthorizedUrl(){
        return "权限不足";
    }
}
